import DBConnection from "../../service/unit/mysql/DBConnection";
import File from "../../service/file/File";

/**
 * @param conn
 * @param oldAnthology 旧文集名
 * @param newAnthology 新文集名
 * @param author
 * */
export async function updateAnthology(conn:DBConnection, oldAnthology:string, newAnthology:string, author:string) {
    const TABLE_NAME_ANTHOLOGY = 'anthology';
    const queryAnthologyResult = await conn.Query.queryWhere(TABLE_NAME_ANTHOLOGY, {anthology:newAnthology});
    const isAnthologyResultNoneNull = queryAnthologyResult.length>0;
    const _oldAnthology = conn.strEncode(oldAnthology);
    const _newAnthology = conn.strEncode(newAnthology);
    const _author = conn.strEncode(author);
    //如果文集表没有该文件就直接插入
    if(isAnthologyResultNoneNull){
        await conn.Update.controllerUpdateAnthology(_newAnthology, _oldAnthology, _author);
        await File.rename(newAnthology,oldAnthology);
        return 'ok';
    }else{
        await conn.Insert.insert(TABLE_NAME_ANTHOLOGY,{anthology:_newAnthology, author:_author});
        await conn.Update.controllerUpdateAnthology(_newAnthology, _oldAnthology, _author);
        await File.rename(newAnthology,oldAnthology);
        return 'ok';
    }
}